﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;

public class LedControllerClient
{
    public static void Main()
    {
        const string method = "PUT";
        const string uri = "http://try.yaler.net/<insert your relay domain here>/led/target";
        const string type = "text/plain";
        const string message = "true";   // ignored for GET requests

        HttpWebRequest request = CreateRequest(method, uri, type,
            message);
        try
        {
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                LogResponse(response);
            }
        }
        catch (Exception e)
        {
            Console.Write(e.ToString());
            Thread.Sleep(Timeout.Infinite);
        }
    }

    static HttpWebRequest CreateRequest(string method,
        string uri, string type, string body)
    {
        var request = (HttpWebRequest)WebRequest.Create(uri);

        // request line
        request.Method = method;

        if ((body != null) && (method != "GET"))
        {
            byte[] buffer = Encoding.UTF8.GetBytes(body);

            // request headers
            request.ContentType = type;
            request.ContentLength = buffer.Length;

            // request body
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(buffer, 0, buffer.Length);
            }
        }
        return request;
    }

    static void LogResponse(HttpWebResponse response)
    {
        // response status line
        Console.WriteLine("HTTP/" + response.ProtocolVersion + " " +
            response.StatusCode);

        // response headers
        string[] headers = response.Headers.AllKeys;
        foreach (string name in headers)
        {
            Console.WriteLine(name + ": " + response.Headers[name]);
        }

        // response body
        var buffer = new byte[response.ContentLength];
        Stream stream = response.GetResponseStream();
        int toRead = buffer.Length;
        while (toRead > 0)
        {
            // already read: buffer.Length - toRead
            int read = stream.Read(buffer, buffer.Length - toRead, toRead);
            toRead = toRead - read;
        }
        char[] chars = Encoding.UTF8.GetChars(buffer);
        Console.WriteLine(new string(chars));
        Thread.Sleep(Timeout.Infinite);
    }
}
